package com.zk.config.api.client;

import java.io.File;
import java.io.IOException;
import org.apache.log4j.Logger;

import com.zk.config.api.constants.Constants;
import com.zk.config.api.util.ComUtil;

public class MappingFile {
	private static Logger logger = Logger.getLogger(MappingFile.class);
	private String filePath;
	private boolean isFile = false;
	private String data;
	public MappingFile(){}
	public MappingFile(String filePath, boolean isFile, String data) {
		this.filePath = filePath;
		this.isFile = isFile;
		this.data = data;
	}
	
	public static void main(String args[]){
		if(args == null || args.length !=3) {
			logger.error("Invalid pramater! args(filePath,isFile,data)");
			return;
		}
		try {
//			String filePath = Constants.mapingDir+"/1.txt";
			String filePath = args[0];
			boolean isFile = Boolean.parseBoolean(args[1]);
			String data = args[2];
			MappingFile.mappingFileToLocal(filePath, isFile, data);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	public static void mappingFileToLocal(String filePath, boolean isFile, String data){
		File file = new File(filePath);
		if(isFile) {
			String parentPath = file.getParent();
			File parentFile = new File(parentPath);
			if(!parentFile.exists()) {
				if(!parentFile.mkdirs()) {
					logger.error("生成映射目录失败！ file="+parentFile.getAbsolutePath());
				}
			}
			if(!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					logger.error(e.getMessage());
					logger.error("生成映射文件失败！ file="+file.getAbsolutePath());
				}
			}
			if(!ComUtil.writeFile(file, data)) {
				logger.error("映射文件写入数据失败！ file="+file.getAbsolutePath());
			}
		} else {
			if(!file.exists()) {
				if(!file.mkdirs()) {
					logger.error("生成映射目录失败！ file="+file.getAbsolutePath());
				}
			}
		}
	}
}
